﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace DoNetToolKit.Algorithm
{
    /****************************************
     * 二分查找法
     ****************************************/
    class BinarySearch
    {
        public void Search()
        {
            int[] a = { 0,1,2,3,4,6,7,8,9};

            for (int i = 0; i < a.Length; i++)
            {
                Console.Write(i+" ");
            }
            Console.WriteLine();

            for (int i = -1; i < 11; i++)
            {
                Console.WriteLine(i+"的index是:"+ DoSearch(a, i));
            }
        }

        public int DoSearch(int[] a, int value)
        {
            int low = 0;
            int high = a.Length - 1;
            while (low <= high)
            {
                int middle = (low + high) / 2;
                if (a[middle] == value)
                {
                    return middle;
                }
                else if (a[middle] < value)
                {
                    low = middle + 1;
                }
                else
                {
                    high = middle-1;
                }
            }
            return -1;
        }

    }
}
